package os_1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

public class os_1_2 {

    public static void main(String[] args) {
        // 创建6个进程，随机生成运行时间
        List<Process> readyQueue = new ArrayList<>();
        Random random = new Random();
        for (int i = 1; i <= 6; i++) {
            int remainingTime = random.nextInt(10) + 1; // 随机生成1到10的运行时间
            readyQueue.add(new Process("Process " + i, remainingTime));
        }

        // 按运行时间从小到大排序（短作业优先）
        Collections.sort(readyQueue, Comparator.comparingInt(Process::getRemainingTime));

        // 调度进程
        while (!readyQueue.isEmpty()) {
            Process currentProcess = readyQueue.get(0); // 选择队首进程
            System.out.println("选中进程: " + currentProcess.getName() +
                    ", 剩余时间: " + currentProcess.getRemainingTime());

            // 运行进程
            currentProcess.run();

            // 更新剩余时间
            currentProcess.setRemainingTime(currentProcess.getRemainingTime() - 1);

            // 如果进程运行时间为0，则移除
            if (currentProcess.getRemainingTime() == 0) {
                readyQueue.remove(currentProcess);
                System.out.println("进程 " + currentProcess.getName() + " 已完成");
            } else {
                // 重新排序
                Collections.sort(readyQueue, Comparator.comparingInt(Process::getRemainingTime));
            }

            // 显示当前就绪队列状态
            System.out.println("当前就绪队列:");
            for (Process p : readyQueue) {
                System.out.println("进程: " + p.getName() +
                        ", 剩余时间: " + p.getRemainingTime());
            }
            System.out.println("-----------------------------");
        }

        System.out.println("所有进程均已完成");
    }

    static class Process {
        private String name;
        private int remainingTime;

        public Process(String name, int remainingTime) {
            this.name = name;
            this.remainingTime = remainingTime;
        }

        public String getName() {
            return name;
        }

        public int getRemainingTime() {
            return remainingTime;
        }

        public void setRemainingTime(int remainingTime) {
            this.remainingTime = remainingTime;
        }

        public void run() {
            System.out.println("正在运行的进程: " + name);
        }
    }
}